/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 15:53:26
 ******************************************************************************/
package cn.com.xy.sms.sdk.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.action.AbsSdkDoAction;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.base.BaseManager;
import cn.com.xy.sms.sdk.db.entity.MatchCacheManager;
import cn.com.xy.sms.sdk.db.entity.SceneRule;
import cn.com.xy.sms.sdk.db.entity.SceneconfigManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.queue.SdkTaskQueue;
import cn.com.xy.sms.sdk.queue.TaskInfo;
import cn.com.xy.sms.sdk.service.baseparse.BaseParseService;
import cn.com.xy.sms.sdk.smsmessage.BusinessSmsMessage;
import cn.com.xy.sms.sdk.title.SmsTitleManager;
import cn.com.xy.sms.sdk.ui.popu.util.ViewUtil;
import cn.com.xy.sms.util.ParseBubbleManager;
import cn.com.xy.sms.util.ParseRichBubbleManager;
import cn.com.xy.sms.util.UUIDUtils;

public class PopupUtil {

    // public static ICheckPopupView checkPopupView=null;

    public static Map<String, Object> parseMsgToPopupWindow(Context context, String phoneNumber, String smsContent, Map<String, Object> valueMap) {

        try {

            if (valueMap != null) {
                String titleNo = (String) valueMap.get("title_num");
                // String bussinessType = valueMap.get("biz_type");
                if (!StringUtils.isNull(titleNo)) {

                    Constant.popupDefault = false;

                    HashMap<String, String> smsTitle = null;
                    SceneRule sceneRule = SceneconfigUtil.getSceneRule(titleNo, SceneconfigManager.SCENE_TYPE_POPUP);
                    if (Constant.Test){
                        smsTitle = SmsTitleManager.getTestBusinessTitleById(Constant.getContext(), titleNo);
                        if (smsTitle == null) {
                            smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo);
                            Constant.popupDefault = true;
                        }
                    } else {
                        if (sceneRule != null) {
                            /* SDK-516 huangzhiqiang 20160630 start */
                            smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo,
                                    sceneRule.Scene_page_config, sceneRule.Func_config);
                            /* SDK-516 huangzhiqiang 20160630 end */
                            if (smsTitle == null) {
                                smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo);
                                Constant.popupDefault = true;
                            }

                        } else {
                            smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo);
                            Constant.popupDefault = true;
                        }
                    }
                    if (smsTitle != null) {
                        BusinessSmsMessage businessSmsMessage = new BusinessSmsMessage();
                        if (Constant.popupDefault) {
                            if (Constant.isDefaultImageExist()) {
                                valueMap.put("view_default_popup", "true");
                            } else {
                                return getResultMap(false, false);
                            }
                        }
                        businessSmsMessage.valueMap = valueMap;
                        try {
                            if (businessSmsMessage.extendParamMap == null) {
                                businessSmsMessage.extendParamMap = new HashMap<String, Object>();
                            }
                            businessSmsMessage.extendParamMap.putAll(valueMap);

                        } catch (Throwable e) {
                            // TODO: handle Throwable
                        }

                        // businessSmsMessage.setType(1);
                        // / businessSmsMessage.type=1;
                        businessSmsMessage.setOriginatingAddress(phoneNumber);
                        businessSmsMessage.setMessageBody(smsContent);
                        // businessSmsMessage.setTimestampMillis(System.currentTimeMillis());
                        // businessSmsMessage.timestampMillis=System.currentTimeMillis();
                        // businessSmsMessage.setBgVis(true);
                        businessSmsMessage.isBgVis = true;
                        // businessSmsMessage.setMsgType(0);
                        // businessSmsMessage.msgType=0;

                        businessSmsMessage.imagePathMap = smsTitle;
                        // businessSmsMessage.setSceneRule(sceneRule);
                        businessSmsMessage.setTitleNo(titleNo);
                        String simIndex = (String) valueMap.get("simIndex");
                        if (!StringUtils.isNull(simIndex)) {
                            try {
                                businessSmsMessage.simIndex = Integer.valueOf(simIndex);
                            } catch (Throwable e) {
                                // e.printStackTrace();
                                LogManager.e(Constant.TAG, "parseMsgToPopupWindow: ", e);

                            }

                        }
                        String msgTime = (String) valueMap.get("msgTime");
                        if (!StringUtils.isNull(msgTime)) {
                            try {
                                businessSmsMessage.msgTime = Long.valueOf(msgTime);
                            } catch (Throwable e) {
                                // e.printStackTrace();
                                LogManager.e(Constant.TAG, "parseMsgToPopupWindow: ", e);

                            }

                        }

                        String simName = (String) valueMap.get("simName");
                        businessSmsMessage.simName = simName;

                        Map<String, Object> handervalueMap = DexUtil.handerValueMap(valueMap, titleNo);
                        isUseDefaultPopup(businessSmsMessage, handervalueMap, titleNo);
                        if (!isPopupAble(handervalueMap, titleNo)) {
                            popupDefault(businessSmsMessage, handervalueMap, titleNo);

                            if (ViewUtil.getChannelType() == 5 && (Constant.popupDefault || valueMap.containsKey("view_forceToDefault_popup"))) {// 神奇工厂,不显示文字的默认弹窗
                                return getResultMap(false, true);
                            }

                            if (!isPopupAble(handervalueMap, titleNo)) {
                                return getResultMap(false, true);
                            } else {

                                SdkTaskQueue.addTask(new TaskInfo(4, "titleNo", titleNo));// 弹窗成功，统计打点
                                startBusinessReceiveSmsActivity(context, businessSmsMessage, valueMap);
                                return getResultMap(true, true);
                            }
                        } else {
                            /*SDK-750 zhaojiangwei 20170330 start*/
                            if(handervalueMap.containsKey("viewPartParam")){
                                businessSmsMessage.putValue("viewPartParam", handervalueMap.get("viewPartParam"));
                            }
                            /*SDK-750 zhaojiangwei 20170330 end*/
                            if (ViewUtil.getChannelType() == 5 && (Constant.popupDefault || valueMap.containsKey("view_forceToDefault_popup"))) {// 神奇工厂,不显示文字的默认弹窗
                                return getResultMap(false, true);
                            }
                            SdkTaskQueue.addTask(new TaskInfo(4, "titleNo", titleNo));// 弹窗成功，统计打点
                            startBusinessReceiveSmsActivity(context, businessSmsMessage, valueMap);
                            return getResultMap(true, true);
                        }
                    } else {
                        return getResultMap(false, true);
                    }
                } else {
                    return getResultMap(false, true);
                }

            }

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "parseMsgToPopupWindow: ", e);

        } finally {
            // 触发情景check队列，情景down队列，资源down队列
            SceneconfigDownloaderQueue.runSceneconfigDownloadQueue();

        }

        return getResultMap(false, true);
    }

    public static boolean isPopupAble(Map<String, Object> valueMap, String titleNo) {
        try {
        	
        	/*SDK-481 hewengao 20160613 start */
        	String viewManagerClass =DuoquUtils.getSdkDoAction().getConfig(AbsSdkDoAction.CONFIG_VIEW_MANAGER_CLASS, null);
        	Class cls = Class.forName(viewManagerClass);
        	//Class cls = Class.forName("cn.com.xy.sms.sdk.ui.popu.util.ViewManger");
        	/*SDK-481 hewengao 20160613 end */
        	
            Method m = cls.getMethod("isPopupAble", Map.class, String.class);
            if (m != null) {
                return (Boolean) m.invoke(cls, valueMap, titleNo);
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "isPopupAble: ", e);

        }
        return false;
    }

    public static void startBusinessReceiveSmsActivity(Context context, BusinessSmsMessage businessSmsMessage, Map<String, Object> valueMap) {
        /*SDK-431 songzhirong 20160530 start*/
        String uuid = UUIDUtils.uniqId();
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.sdk.util.PopupUtil", "startBusinessReceiveSmsActivity", context, businessSmsMessage,valueMap);
            /*SDK-431 songzhirong 20160530 end*/
            if (businessSmsMessage != null) {// 情景短信
                businessSmsMessage.valueMap = valueMap;
                /*
                 * if (ViewUtil.getChannelType() == 3) {
                 * PopupMsgManager.businessSmsList.clear(); }
                 */
                PopupMsgManager.businessSmsList.addLast(businessSmsMessage);
            } else {
                // 非情景短信弹窗
                PopupMsgManager.addThirdPopupMsgData(valueMap);
            }

            SdkTaskQueue.addTask(new TaskInfo(12, "state", String.valueOf(RecordFunctionUtil.POP_WINDOW_STATE)));// 弹窗标记状态

            Intent intent2 = new Intent();
            intent2.setClassName(context, "cn.com.xy.sms.sdk.ui.popu.BusinessReceiveSmsActivity");
            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent2);
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "startBusinessReceiveSmsActivity: ", e);

        }finally{
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.sdk.util.PopupUtil", "startBusinessReceiveSmsActivity", context, businessSmsMessage,valueMap);
            /*SDK-431 songzhirong 20160530 end*/

        }

    }

    public static void popupDefault(BusinessSmsMessage businessSmsMessage, Map<String, Object> valueMap, String titleNo) {
        try {

            if (businessSmsMessage != null && valueMap != null) {
                valueMap.put("view_forceToDefault_popup", "true");

                if (ViewUtil.getChannelType() == 2 || ViewUtil.getChannelType() == 8) {// 中兴默认弹窗
                    valueMap.put("View_fdes", "H103102;B502513,10236113;F904");
                } else if (ViewUtil.getChannelType() == 5) {
                    valueMap.put("View_fdes", "H113;B502,10340013;F908906");
                } else {// 其他渠道的默认弹窗
                    valueMap.put("View_fdes", "H101;B502,11125213;F901");
                }
                valueMap.put("view_title_name", valueMap.get("title_name"));
                valueMap.put("View_viewid", "001");

                if (Constant.isDefaultImageExist()) {
                    HashMap<String, String> smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo);
                    if (smsTitle != null) {
                        businessSmsMessage.imagePathMap = smsTitle;
                    }
                }

            }

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "popupDefault: " , e);

        }
    }

    public static void isUseDefaultPopup(BusinessSmsMessage businessSmsMessage, Map<String, Object> handervalueMap, String titleNo) {

        try {
            if (businessSmsMessage != null && handervalueMap != null) {
                /*
                 * handervalueMap.put("view_forceToDefault_popup", "true");
                 * handervalueMap.remove("View_hideHead");
                 * handervalueMap.remove("View_hideBody");
                 * handervalueMap.remove("View_hideBottom");
                 * handervalueMap.remove("View_bottomid");
                 * handervalueMap.put("View_fdes", "100100114114007007");
                 * handervalueMap.put("view_title_name",
                 * handervalueMap.get("title_name"));
                 * handervalueMap.put("text_color", "#238acc");
                 */
                // 短信可以识别，但是没有配置映射关系，用默认弹窗
                if (Constant.isDefaultImageExist() && handervalueMap.containsKey("view_forceToDefault_popup")) {
                    HashMap<String, String> smsTitle = SmsTitleManager.getBusinessTitleById(Constant.getContext(), titleNo);
                    if (smsTitle != null) {
                        businessSmsMessage.imagePathMap = smsTitle;
                    }
                }
                /*SDK-750 zhaojiangwei 20170330 start*/
                for (String key : handervalueMap.keySet()) {
                    if(businessSmsMessage.valueMap == null || businessSmsMessage.valueMap.containsKey("key")){
                        return;
                    }
                    businessSmsMessage.valueMap.put(key, handervalueMap.get(key));
                }
                /*SDK-750 zhaojiangwei 20170330 end*/
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "isUseDefaultPopup: ", e);

        }
    }

    public static Map<String, Object> getResultMap(boolean show, boolean smsRecog) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("Result", show);
        resultMap.put("recogResult", smsRecog);

        return resultMap;
    }

    public static Map<String, Object> getResultMap(Map<String, Object> resultMap, String phoneNumber, String smsContent, Map<String, Object> valueMap, Context context) {

        if (ViewUtil.getChannelType() == 3 && ((Boolean) resultMap.get("Result") == false)) {
            if (phoneNumber != null && valueMap != null) {
                // 联想渠道,需要弹窗联想自己的默认数据
                Object msgId = valueMap.get("msgId");
                Object simIndex = valueMap.get("simIndex");
                Object simName = valueMap.get("simName");
                Object msgTime = valueMap.get("msgTime");
                Object uri = valueMap.get("uri");
                valueMap.clear();
                valueMap.put("msgId", msgId);
                valueMap.put("simIndex", simIndex);
                valueMap.put("simName", simName);
                valueMap.put("msgTime", msgTime);
                valueMap.put("phoneNumber", phoneNumber);
                valueMap.put("smsContent", smsContent);
                valueMap.put("uri", uri);
                // 显示
                startBusinessReceiveSmsActivity(context, null, valueMap);
                resultMap.put("Result", true);
            }
        }

        return resultMap;
    }

    public static BusinessSmsMessage getMsg(String phone, String body) {

        if (!StringUtils.isNull(phone) && !StringUtils.isNull(body)) {
            BusinessSmsMessage smsMessage = new BusinessSmsMessage();
            // smsMessage.type=1;
            smsMessage.setOriginatingAddress(phone);
            smsMessage.setMessageBody(body);
            smsMessage.isBgVis = true;
            // smsMessage.msgType=0;

            return smsMessage;
        }
        return null;
    }

    // public static boolean isPopupAble(Map<String, Object>
    // handervalueMap,String titleNo){
    // try {
    // LogManager.i("handervalueMap", handervalueMap.toString());
    // if(handervalueMap==null||StringUtils.isNull(titleNo))return false;
    // int viewid = -1;
    // if(handervalueMap.containsKey("View_viewid"))
    // {
    // String id = (String)handervalueMap.get("View_viewid");
    // if(LogManager.debug)
    // {
    // LogManager.i("PopupMsgManager", "View_viewid="+id);
    // }
    // if(!StringUtils.isNull(id))
    // {
    // viewid = Integer.parseInt(id);
    // if(viewid==ViewManger.OneSide_PopupView)
    // {
    // int[] arr =
    // ViewManger.getViewNo((String)handervalueMap.get("View_fdes"));
    // LogManager.i("PopupMsgManager",
    // "View_fdes="+(String)handervalueMap.get("View_fdes"));
    // int headPartId = ViewManger.getHeadUIPartId(arr[0], arr[4]);
    // LogManager.i("PopupMsgManager", "headPartId="+headPartId);
    // if(headPartId==-1)return false;
    // int bodyPartId = ViewManger.getBodyUIPartId(arr[2],arr[5]);
    // LogManager.i("PopupMsgManager", "bodyPartId="+bodyPartId);
    // if(bodyPartId==-1)return false;
    // int headLayoutId = ViewManger.getLayoutid(arr[1]);
    // LogManager.i("PopupMsgManager", "headLayoutId="+headLayoutId);
    // if(headLayoutId==-1)return false;
    // int bodyLayoutId = ViewManger.getLayoutid(arr[3]);
    // LogManager.i("PopupMsgManager", "bodyLayoutId="+bodyLayoutId);
    // if(bodyLayoutId==-1)return false;
    //
    // return true;
    // }
    // }
    // }
    // else{
    // if(LogManager.debug)
    // {
    // LogManager.i("PopupMsgManager", "View_viewid为空了");
    // }
    // }
    //
    // return false;
    // } catch (Throwable e) {
    // e.printStackTrace();
    // }
    // return false;
    //
    // }
    //
    /*SDK-407 hewengao 20160425 start*/
   /**
    * 是否是固话正则
    */
   final static Pattern FIXED_PHONE  = java.util.regex.Pattern.compile("(?<![\\-0-9])0\\d{2,3}-?\\d{7,8}(?!\\d)");
   /*SDK-407 hewengao 20160425 end*/
   
    public static boolean isEnterpriseSms(Context ctx, String phoneNumber, String smsContent, Map<String, String> extend) {
        phoneNumber = StringUtils.getPhoneNumberNo86(phoneNumber);
        if (StringUtils.isNull(phoneNumber)) {
            return false;
        }

        phoneNumber = phoneNumber.replace(" ", "").replace("-", "");

        String allArr[] = { "10088", "10198", "101901", "123662", "12306", "12110110", "121100020", "11888", "11868", "1186666", "118388", "118200", "118114", "118100", "118067", "11803080", "11185", "11183", "13800138000", "095583", "1252004411", "12520", "12520029", "12520035", "125200353", "125200352", "125200304", "125200351", "12520010", "12520021", "125200303", "1252003300000", "12520032", "125200302", "12520028", "12520038", "12520024", "12520036", "125200301", "12520027", "125200354", "1252003300000", "053287003810" };
        int len = allArr.length;

        for (int i = 0; i < len; i++) {
            if (allArr[i].equals(phoneNumber)) {
                return true;
            }
        }
        String[] startArr = { "96", "95", "106", "10178", "10086", "1006", "1001", "1000", "116114" };
        len = startArr.length;
        for (int i = 0; i < len; i++) {
            if (phoneNumber.startsWith(startArr[i])) {
                return true;
            }
        }

        if (phoneNumber.startsWith("12520030") && phoneNumber.length() <= 10) {
            // 开头总长度不超过10
            return true;
        }
        if (phoneNumber.startsWith("12520036") && phoneNumber.length() == 19) {
            // 开头且后面是手机号
            return StringUtils.sj(phoneNumber.replace("12520036", ""));
        }
        /*SDK-418 hewengao 20160428 start*/
        if(extend != null && extend.containsKey("FIXED_PHONE") && !"false".equalsIgnoreCase(extend.get("FIXED_PHONE"))){
            return isFixedPhoneInner(phoneNumber);
        }
        return false;
        /*SDK-418 hewengao 20160428 end*/
    }
    /*SDK-407 hewengao 20160425 start*/
   /**
    * 是否固定电话 
    * @param phoneNumber
    * @return
    */
    public static boolean isFixedPhone(String phoneNumber){
    	try{
            ClassLoader dexClassLoader = DexUtil.getDexClassLoader();
            if (dexClassLoader != null) {
    		    Class onlineParseImplClass = dexClassLoader.loadClass("cn.com.xy.sms.sdk.Iservice.OnlineParseImpl"); 
    		    Method md = onlineParseImplClass.getMethod("isFixedPhone", String.class);
    		    return (Boolean)md.invoke(onlineParseImplClass, phoneNumber);
            }
    	}catch(Throwable e){
    		LogManager.e(Constant.TAG, "PopupUtil.isFixedPhone", e);
    	}
		return isFixedPhoneInner(phoneNumber);
    }
    
    private static boolean isFixedPhoneInner(String phoneNumber){
    	try {
			// 是否是固定电话
			Matcher matcher = FIXED_PHONE.matcher(phoneNumber);
			if (matcher.find()) {
				return true;
			}
		} catch (Throwable e) {
			LogManager.e("xiaoyuan", "FIXED_PHONE: ",e);
		}
		return false;
    }
    /*SDK-407 hewengao 20160425 end*/
    
    public static int getActionCode(String action) {
        int type = -1;
        try {
            if (!StringUtils.isNull(action)) {
                if (action.equalsIgnoreCase("url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("reply_sms")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("reply_sms_fwd")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("call_phone") || "call".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_CALL;
                } else if (action.equalsIgnoreCase("reply_sms_open")) {
                    type = Constant.ACTION_SMS;
                } else if (action.equalsIgnoreCase("access_url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("down_url") || "download".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("send_email")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("weibo_url")) {
                    type = Constant.ACTION_URL;
                } else if (action.equalsIgnoreCase("map_site") || "open_map".equalsIgnoreCase(action) || "open_map_list".equalsIgnoreCase(action) || "open_map_browser".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_MAP;
                } else if (action.equalsIgnoreCase("chong_zhi") || action.equalsIgnoreCase("recharge") || "zfb_recharge".equalsIgnoreCase(action) || "WEB_CHONG_ZHI".equalsIgnoreCase(action) || "WEB_RECHARGE_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_PAY_CHONGZHI;
                } else if ("repayment".equalsIgnoreCase(action) || "zfb_repayment".equals(action) || "WEB_REPAYMENT".equalsIgnoreCase(action) || "WEB_REPAYMENT_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_PAY_HUANKUAN;
                } else if (action.equalsIgnoreCase("copy_code")) {
                    type = Constant.ACTION_COPY_CODE;
                } else if ("open_app".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_OPEN_APP;
                } else if ("time_remind".equalsIgnoreCase(action) || "sdk_time_remind".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_DATE_REMIND;
                } else if ("pay_water_gas".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_WATER_GAS;
                } else if ("WEB_TRAFFIC_ORDER".equalsIgnoreCase(action) || "WEB_TRAFFIC_CHOOSE".equalsIgnoreCase(action) || "WEB_PURCHASE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_TRAFFIC_ORDER;
                } else if ("WEB_QUERY_EXPRESS_FLOW".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_EXPRESS_FLOW;
                } else if ("WEB_QUERY_FLIGHT_TREND".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_FLIGHT_TREND;
                } else if ("WEB_INSTALMENT_PLAN".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_INSTALMENT_PLAN;
                } else if ("WEB_TRAIN_STATION".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_TRAIN_STATION;
                } else if ("WEB_NEAR_SITE".equalsIgnoreCase(action) || "near_site".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_NEAR_SITE;
                } else if ("WEB_LIVE_CHOOSE".equalsIgnoreCase(action)) {
                    type = Constant.ACTION_LIVE_SERVER;
                } else {
                    type = Constant.ACTION_OTHER;
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
            LogManager.e("XIAOYUAN", "PopupUtil getActionCode error: ", e);
        }

        return type;
    }

    /*SDK-473 hewengao 20160603 start */
    /**
     * 启动web Activity
     * 
     * @param context
     * @param jsobj
     * @param actionType
     */
	public static boolean startWebActivity(Context context, JSONObject jsobj,
			String actionType, String phoneNum) {
		return AbsSdkDoAction.openStartWebActivity(context, jsobj, actionType, phoneNum, null);
	}
	 /*SDK-473 hewengao 20160603 end */

    /**
     * 算法解析的结果封装成,短信到会话卡片需要的结果
     * 
     * @param context
     * @param msgId
     *            短消息ID
     * @param phoneNumber
     *            短信接入码,短信发送方号码
     * @param smsCenterNum
     *            短信发送方,短信中心号码
     * @param smsContent
     *            短信内容
     * @param smsReceiveTime
     *            短信接收时间
     * @param returnCacheType
     *            返回数据的缓存类型 1:返回SDK缓存标识 2:返回SDK识别结果 由开发者保存sdk标识或识别结果.
     * @param valueMap
     *            识别算法分析的结果
     * @return Map<String,Object> 包含key CACHE_SDK_MSG_ID 识别结果标识ID
     *         returnCacheType=1时 CACHE_SDK_MSG_RESULT:识别结果 value:jsonstring
     *         returnCacheType=2时
     * @throws Throwable
     */

    public static Map<String, Object> parseMsgToBubbleCardResult(Context context, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, Object> valueMap, boolean resultAddToMemory) throws Exception {
        try {
            // LogManager.d("BubbleCardResult", "valueMap: "+valueMap);
            if (valueMap == null) {
                LogManager.e("xiaoyuan_test", "valueMap null .msgId:  ", null);
                return null;
            }
            // LogManager.e("BubbleCardResult",
            // "valueMap success. msgId: "+msgId);
            valueMap.remove("viewPartParam");
            long start = System.currentTimeMillis();
            Map<String, Object> res = DexUtil.handerBubbleValueMap(valueMap);
            LogManager.d("kk", "valueMap handerValueMap="+res);
            long end = System.currentTimeMillis();
//            LogManager.d("xiaoyuan_test", "handerBubbleValueMap time:" + (end - start));

            long bubbleLasttime = System.currentTimeMillis();
            int parseStatu = 0;
            if (res != null) {
                if (valueMap.containsKey(Constant.KEY_IS_SAFE_VERIFY_CODE)) {
                    res.put(Constant.KEY_IS_SAFE_VERIFY_CODE, String.valueOf(valueMap.get(Constant.KEY_IS_SAFE_VERIFY_CODE)));
                }

                // LogManager.d("BubbleCardResult",
                // "valueMap handerValueMap success. ");
                // 此处check是否能正常显示汽泡视图,并同时需要检测汽泡所需的要配置数据是否正常.将配置数据一并,加入返回的数据中.
                String titleNo = (String) res.get("title_num");
                // LogManager.e("BubbleCardResult",
                // "valueMap res success. .msgId:  "+msgId+" titleNo: "+titleNo);
                // PrintTestLogUtil.printTestLog("parseMsgToBubbleCardResult",
                // "titleNo="+titleNo);
                HashMap<String, String> bubleSmsTitle = SmsTitleManager.getBubleSmsTitle(titleNo);
                end = System.currentTimeMillis();
//                LogManager.d("xiaoyuan_test", "getBubleSmsTitle time:" + (end - start));
                // PrintTestLogUtil.printTestLog("parseMsgToBubbleCardResult",
                // "BubleSmsTitle="+BubleSmsTitle);

                boolean bubleSmsTitleIsNotNull = bubleSmsTitle != null && !bubleSmsTitle.isEmpty();

                // // 华为渠道不检查是否有情景配置
                if (ViewUtil.getChannelType() == 7 || ViewUtil.getChannelType() == 17 || bubleSmsTitleIsNotNull) {
                    // if (bubleSmsTitleIsNotNull) {
                    if (bubleSmsTitleIsNotNull) {
                        res.putAll(bubleSmsTitle);
                    }
                    if (isPopupAble(res, titleNo)) {// 表示汽泡视图准备就绪,可能提供给开发者使用
                        phoneNumber = StringUtils.getPhoneNumberNo86(phoneNumber);
                        /* SDK-647 likuangkuang 20161104 start if remote call, it is necessary to get JSONObject using the default constructor */
                        res.remove("viewPartParam");
                        JSONObject jsobj = new JSONObject(res);
                        /* SDK-647 likuangkuang 20161104 end */
                        
                        long sdkMsgId = 0;
                        // 此处需要将json string入库至sdk缓存,并返回SDK_MSG_ID 返回给开发者缓存

                        String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
                        MatchCacheManager.removeUselessKey(jsobj);
                        if (!StringUtils.isNull(msg_num_md5)) {
                            ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", phoneNumber, "scene_id", titleNo, "msg_id", msgId, "bubble_result", jsobj.toString(), "save_time", String.valueOf(smsReceiveTime), "bubble_lasttime", String.valueOf(System.currentTimeMillis()), "urls", jsobj.optString(Constant.URLS));

                            sdkMsgId = MatchCacheManager.insertOrUpdate(matchCache, 2);
                            /* SDK-559 huangzhiqiang 20160725 start */
                            LogManager.d("xiaoyuan_test", "MatchCacheManager insertOrUpdate sdkMsgId:", String.valueOf(sdkMsgId));
                            /* SDK-559 huangzhiqiang 20160725 end */
                        }
                        res.clear();
                        if (returnCacheType == 1) {

                            res.put("CACHE_SDK_MSG_ID", sdkMsgId);
                            // res.put("View_fdes",
                            // JsonUtil.getValueFromJsonObject(jsobj,
                            // "View_fdes"));
                        } else {
                            // res.clear();
                            // 返回jsonString给开发者,并由开发者自行缓存
                            res.put("CACHE_SDK_MSG_RESULT", jsobj.toString());
                            // res.put("View_fdes",
                            // JsonUtil.getValueFromJsonObject(jsobj,
                            // "View_fdes"));
                        }
                        res.put("View_fdes", JsonUtil.getValueFromJsonObject(jsobj, "View_fdes"));

                        // if(resultAddToMemory &&
                        // ParseBubbleManager.equalPhoneNum(phoneNumber)){
                        // LogManager.e("duoqu_test",
                        // "resultAddToMemory ParseBubbleManager.equalPhoneNum addEffectiveBubbleData msgId:"+msgId);
                        if (resultAddToMemory) {
                            ParseRichBubbleManager.addEffectiveBubbleData(phoneNumber, msgId, jsobj);
                        }
                        res.put("BUBBLE_JSON_RESULT", jsobj);
                        res.put("parseStatu", 1);
                        // end = System.currentTimeMillis();
                        // LogManager.d("duoqu_test",
                        // "MatchCacheManager.insertOrUpdate time:"+(end-start));
                        return res;
                    } else {
                        /*SDK-674 hewengao 20161114 start*/
                        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," parseMsgToBubbleCardResult  isPopupAble is faild",null);
                        /*SDK-674 hewengao 20161114 end*/
                        LogManager.d("xiaoyuan_test", "valueMap isPopupAble faild.msgId: ", msgId);
                        // isPopupAble faild
                        parseStatu = -3;
                    }
                } else {
                     /*SDK-674 hewengao 20161114 start*/
                    DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," parseMsgToBubbleCardResult  BubleSmsTitle is null",null);
                   /*SDK-674 hewengao 20161114 end*/
                    LogManager.d("xiaoyuan_test", "valueMap BubleSmsTitle faild.msgId: ", msgId);
                    // BubleSmsTitle faild
                    parseStatu = -2;
                }

                // 脚本已识别但是找不到资源的情况下，查询tb_match_cache是否已存在对应数据，
                // 无数据则代表是第一次进行识别，将最后识别时间提前5小时58分钟，使短信在2分钟后重新进行识别
                // 已经存在数据代表2分钟后识别仍然没有找到资源，则在7分钟后重新识别
                if (MatchCacheManager.queryDataCount(msgId, MatchCacheManager.getMD5(phoneNumber, smsContent)) == 0) {
                    bubbleLasttime = System.currentTimeMillis() - (DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, 6 * 3600 * 1000L) - 120000L);// 2分钟
//                    LogManager.e("xiaoyuan_test", "脚本已识别但是找不到资源valueMap res faild.msgId: " + msgId + "bubbleLasttime=" + bubbleLasttime + "time=" + new java.util.Date(bubbleLasttime).toLocaleString(), null);
                } else {
                    bubbleLasttime = System.currentTimeMillis() - (DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, 6 * 3600 * 1000L) - 420000L);// 7分钟
//                    LogManager.e("xiaoyuan_test", "脚本已识别隔2分钟后仍然查不到资源valueMap res faild.msgId: " + msgId + "bubbleLasttime=" + bubbleLasttime, null);
                }
                // end = System.currentTimeMillis();
                // LogManager.d("duoqu_test",
                // "MatchCacheManager.queryDataCount time:"+(end-start));
            } else {
                /*SDK-674 hewengao 20161114 start*/
                DuoquUtils.getSdkDoAction().logInfo(Constant.TAG," parseMsgToBubbleCardResult is null",null);
                /*SDK-674 hewengao 20161114 end*/
                LogManager.d("xiaoyuan_test", "valueMap res faild.msgId: ",msgId);
            }
            String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
            if (!StringUtils.isNull(msg_num_md5)) {// 不能处理的也需要加入缓存.
                ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", StringUtils.getPhoneNumberNo86(phoneNumber), "scene_id", "", "msg_id", msgId, "bubble_result", "", "save_time", String.valueOf(smsReceiveTime), "bubble_lasttime", String.valueOf(bubbleLasttime));
                MatchCacheManager.insertOrUpdate(matchCache, 2);
            }
            // if(resultAddToMemory &&
            // ParseBubbleManager.equalPhoneNum(phoneNumber)){
            if (resultAddToMemory) {
                ParseRichBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
            }
            // end = System.currentTimeMillis();
            // LogManager.d("duoqu_test",
            // "MatchCacheManager.last  @@@@@  time:"+(end-start));
            if (parseStatu != 0 && res != null) {
                res.clear();
                res.put("parseStatu", parseStatu);
                return res;
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "parseMsgToBubbleCardResult: ", e);

        } finally {
            // 触发情景check队列，情景down队列，资源down队列
            SceneconfigDownloaderQueue.runSceneconfigDownloadQueue();
        }
        return null;
    }

    /**
     * 算法解析的结果封装成,短信到会话卡片需要的结果
     * 
     * @param context
     * @param msgId
     *            短消息ID
     * @param phoneNumber
     *            短信接入码,短信发送方号码
     * @param smsCenterNum
     *            短信发送方,短信中心号码
     * @param smsContent
     *            短信内容
     * @param smsReceiveTime
     *            短信接收时间
     * @param returnCacheType
     *            返回数据的缓存类型 1:返回SDK缓存标识 2:返回SDK识别结果 由开发者保存sdk标识或识别结果.
     * @param valueMap
     *            识别算法分析的结果
     * @return Map<String,Object> 包含key CACHE_SDK_MSG_ID 识别结果标识ID
     *         returnCacheType=1时 CACHE_SDK_MSG_RESULT:识别结果 value:jsonstring
     *         returnCacheType=2时
     * @throws Throwable
     */

    public static Map<String, Object> parseMsgToSimpleBubbleResult(Context context, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, Object> valueMap, boolean resultAddMemory,Map<String, String> extend) throws Exception {
        if (valueMap == null) {
            return null;
        }
//        String data = (String) valueMap.get("ADACTION");
        String data = BaseParseService.getAdAction(valueMap, extend);
        Map<String, Object> res = null;
        if (returnCacheType == 1) {// xiao yuan sdk persistent simple bubble
                                   // data
            long sdkMsgId = -1;
            String msg_num_md5 = MatchCacheManager.getMD5(phoneNumber, smsContent);
            if (!StringUtils.isNull(msg_num_md5)) {

                ContentValues matchCache = BaseManager.getContentValues(null, "msg_num_md5", msg_num_md5, "phonenum", StringUtils.getPhoneNumberNo86(phoneNumber), "msg_id", msgId, "session_reuslt", data == null ? "" : data, "save_time", String.valueOf(smsReceiveTime), "session_lasttime", String.valueOf(System.currentTimeMillis()));
                sdkMsgId = MatchCacheManager.insertOrUpdate(matchCache, 1);
            }
            if (data != null) {
                res = new HashMap<String, Object>();
                res.put("CACHE_SDK_MSG_ID", sdkMsgId);
                res.put("CACHE_SDK_MSG_SIMPLE_RESULT", data);
            }
        } else {
            if (data != null) {
                res = new HashMap<String, Object>();
                res.put("CACHE_SDK_MSG_SIMPLE_RESULT", data);
            }
        }
        if (resultAddMemory && ParseBubbleManager.equalPhoneNum(phoneNumber)) {
            try {
                if (data != null) {
                    JSONArray simpleArrData = new JSONArray(data);
                    ParseBubbleManager.addEffectiveBubbleData(phoneNumber, msgId, simpleArrData);
                } else {
                    ParseBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
                }
            } catch (Throwable e) {
                ParseBubbleManager.addInvalidBubbleData(phoneNumber, msgId);
                // e.printStackTrace();
                LogManager.e(Constant.TAG, "parseMsgToSimpleBubbleResult: ", e);

            }

        }
        return res;
    }

    public static String getValue() {
        try {
            /* SDK-570 huangzhiqiang 20160802 start */
            String res = AppUtil.assemble();
            res = StringUtils.handlerAssemble(res);
            /* SDK-570 huangzhiqiang 20160802 end */
            return StringUtils.decode(res);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "PopupUtil getValue error", e);
        }
        return "";
    }
}
